import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入登陆
// import Login from '@/views/login'

//  主页
import Layout from '@/views/layout'
// 二级路由
// 导入本地token
import { getToken } from '../api/usertoken.js'
const Login = () => import('@/views/login')
const Home = () => import('@/views/Home')
const Articles = () => import('@/views/Articles')
const AddArticle = () => import('@/views/AddArticle')
const Images = () => import('@/views/Images')
const Comment = () => import('@/views/Comment')
const Fans = () => import('@/views/Fans')
const Setting = () => import('@/views/Setting')
const NotFound = () => import('@/views/NotFound')

Vue.use(VueRouter)

const routes = [
  // 登陆
  { path: '/Login', component: Login, name: 'Login' },
  // 主页
  {
    path: '/',
    component: Layout,
    // name: 'Layout',
    children: [
      // 默认主页
      { path: '/', component: Home, name: 'Home' },
      // 内容管理
      { path: '/articles', component: Articles, name: 'Articles' },
      // 发布文章
      { path: '/addArticle', component: AddArticle, name: 'AddArticle' },
      { path: '/addArticle/:id', component: AddArticle, name: 'AddArticle' },
      // 素材管理
      { path: '/images', component: Images, name: 'Images' },
      // 评论管理
      { path: '/comment', component: Comment, name: 'Comment' },
      // 粉丝管理
      { path: '/fans', component: Fans, name: 'Fans' },
      // 个人设置
      { path: '/Setting', component: Setting, name: 'Setting' }
    ]
  },
  // 404页面
  { path: '*', component: NotFound, name: 'NotFound' }
]
// 处理新版router异常
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => (console.warn(err)))
}

const router = new VueRouter({
  routes
})
// 设置前置全局守卫
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (!token && to.path !== '/login') {
    return next('/login')
  } else if (token && to.path === '/login') {
    return next('/')
  }
  next()
})
export default router
